<template>
    <div class="container">
        <div class="aside">
            <el-card style="height: 160px; ">
                <template #header>
                    <div style="display: flex;justify-content: space-between;">
                        <span> 最新通知</span>
                        <el-button v-if="root" link type="success" @click="openInformDialog">发布通知</el-button>
                    </div>
                </template>
                <h1 style="text-align: center;line-height: 60px;" v-if="!informDate.announment.length">暂无通知</h1>
                <div class="demo-collapse" v-else>
                    <el-popover v-for="item in informDate.announment" placement="left" :width="200" trigger="click"
                        :content="item.content">
                        <template #reference>
                            <p style="text-align: center; line-height: 25px;"><el-button type="warning" link>{{ item.title
                            }}</el-button></p>
                        </template>
                    </el-popover>
                </div>
            </el-card>
            <el-card style="min-height: 600px; ">
                <template #header>
                    <div class="card-header">
                        <b> 猜你喜欢</b>
                    </div>
                </template>
                <el-table :data="tableInfo.recommentArticles" style="width: 100%" border>
                    <el-table-column prop="title" label="标题" align="center">
                        <template #default="scope">
                            <el-tooltip :content="`${scope.row.title}`" placement="top">
                                <el-button type="primary" link @click="toArticleDetail(scope.row.id)">{{ scope.row.title }}
                                </el-button>
                            </el-tooltip>
                        </template>
                    </el-table-column>
                    <el-table-column label="作者" align="center">
                        <template #default="scope">
                            <span>{{ scope.row.author }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="简介" align="center">
                        <template #default="scope">
                            <div class="introduction-box"> <span>{{ scope.row.introduction }}</span></div>
                        </template>
                    </el-table-column>
                </el-table>
                <el-radio-group v-model="tableInfo.orderDto.sort" @change="initRecommentArticle()">
                    <el-radio label="liker">点赞数</el-radio>
                    <el-radio label="beCollected">收藏数</el-radio>
                    <el-radio label="viewer">浏览数</el-radio>
                    <el-radio label="comment">评论数</el-radio>
                </el-radio-group>
                <el-switch v-model="tableInfo.orderDto.order" class="mb-2" active-value="DESC" inactive-value="ASC"
                    style="--el-switch-on-color:#ff4949; --el-switch-off-color:#13ce66" active-text="降序" inactive-text="升序"
                    @change="initRecommentArticle()" />
            </el-card>
        </div>
        <el-card class="table-container">
            <template #header>
                <div style="display: flex;justify-content:space-between;">
                    <div style="width: 40%;">
                        <el-input v-model.trim="tableInfo.keyword" placeholder="搜索题目" class="input-with-select"
                            @blur="initTableInfo" @keyup.enter.native="initTableInfo">
                            <template #append>
                                <el-button :icon="Search" style="background-color: #409eff;color: #fff;"
                                    @click="initTableInfo"></el-button>
                            </template>
                        </el-input>
                    </div>
                    <div style="display: flex;align-items: center;">
                        <el-checkbox v-model="tableInfo.onlyMe" label="我的" size="small" @change="initTableInfo()"
                            style="margin-right: 5px;" />
                    </div>

                </div>
            </template>
            <el-table :data="tableInfo.articles" border empty-text="暂无数据">
                <el-table-column prop="title" label="标题" align="center">
                    <template #default="scope">
                        <div style="text-align: center">
                            <el-button type="primary" link @click="toArticleDetail(scope.row.id)">{{ scope.row.title }}
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="category" label="类别" align="center" />
                <el-table-column prop="author" label="作者" align="center" />
            </el-table>
            <div class="pagination">
                <el-pagination background layout="prev, pager, next, jumper, ->, total ,sizes"
                    :page-sizes="['5', '10', '20']" @size-change="sizeChange" @current-change="currentChange"
                    :page-size="tableInfo.pageSize" :total="tableInfo.total" small />
            </div>
        </el-card>
        <el-card class="right-contaienr">
            <template #header>
                文章种类
            </template>
            <div ref="pieChartBox" style="width: 100%;min-height: 250px; "></div>
            <div ref="barChartBox" style="width: 100%;min-height: 250px; "></div>
        </el-card>
    </div>

    <el-dialog v-model="informDate.announcementDialog" :show-close="false" @close="resetForm(announcementFormRef)">
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">发布通知</h4>
            </div>
        </template>
        <el-form label-width="100px" :rules="rules" ref="announcementFormRef" :model="informDate">
            <el-form-item label="标题：" prop="title">
                <el-input v-model="informDate.title"></el-input>
            </el-form-item>
            <el-form-item label="内容：" prop="content">
                <el-input v-model="informDate.content"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="pubishAnnouncent(announcementFormRef)">
                    发送
                </el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
</template> 
<script setup lang='ts' name="home">
import { reactive, ref } from 'vue'
import { onMounted, nextTick } from 'vue';
import { findArticles, addAnnouncement, getAnnouncement } from '@/api';
import { ElButton, type FormInstance, type FormRules, ElInput, ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/stores';
import { Search } from '@element-plus/icons-vue';
import { objectToArray } from '@/utils'
import { useRouter } from 'vue-router';
import * as echarts from 'echarts'
import * as _ from 'lodash'
var pieChart: any;
var barChart: any;
const router = useRouter()
const informDate = reactive<{ announcementDialog: boolean, content: string, title: string, announment: Array<{ content: string, title: string }> }>({
    announcementDialog: false,
    announment: [],
    content: '',
    title: '',

})


const announcementFormRef = ref<FormInstance>()
const pieChartBox = ref<HTMLDivElement>()
const barChartBox = ref<HTMLDivElement>()
const userInfoStore = useUserInfoStore()
const { uuid, root } = userInfoStore.userInfo
const tableInfo = reactive<any>({
    articles: [],
    pageSize: 10,
    page: 1,
    publish_status: 2,
    total: 0,
    keyword: '',
    orderDto: {
        sort: 'liker',
        order: 'DESC'
    },
    recommentArticles: [],
    limit: 8,
    groupDate: [],
    onlyMe: false,
    drawerVisable: false
})

const rules = reactive<FormRules>({
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入通知内容', trigger: 'blur' },
    ],
})

onMounted(async () => {
    initTableInfo()
    initRecommentArticle()
    initAccountment()
})

const initTableInfo = async () => {
    const { pageSize, page, publish_status, keyword } = tableInfo
    const data: any = {
        publish_status, keyword, pageSize, page,
    }
    if (tableInfo.onlyMe) {
        data.uuid = uuid
    }
    try {
        const res = await findArticles(data)
        const { articles, total } = res.data.data

        tableInfo.articles = articles
        tableInfo.total = total
        tableInfo.groupDate = _.groupBy(tableInfo.articles, 'category')


        const chartData = Object.entries(tableInfo.groupDate).map(([group, items]) => ({
            name: group,
            value: (items as any).length,
        }));
        nextTick(() => {
            if (!pieChart) {
                pieChart = echarts.init(pieChartBox.value as HTMLDivElement);
            }
            // 绘制图表 
            pieChart.setOption({
                series: [
                    {
                        name: '数量',
                        type: 'pie',
                        data: chartData,
                        radius: '60%',
                    }
                ]
            });
            if (!barChart) {
                barChart = echarts.init(barChartBox.value as HTMLDivElement);
            }
            //柱状图
            barChart.setOption({
                xAxis: {
                    type: 'category',
                    data: objectToArray(tableInfo.groupDate)[0],
                    axisLabel: {
                        rotate: -45, // 逆时针旋转 45 度
                    },
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '数量',
                        data: objectToArray(tableInfo.groupDate)[1].map(item => item.length),
                        type: 'bar',
                        label: {
                            show: true, // 显示标签
                            position: 'top', // 标签位置
                            formatter: '{c}', // 标签内容
                        },
                        showBackground: true,
                        backgroundStyle: {
                            color: 'rgba(180, 180, 180, 0.2)'
                        }
                    }
                ]
            });
        })
    } catch (error) {
    }
}

const initRecommentArticle = async () => {
    //获取自己文章展示
    try {
        const { limit, orderDto } = tableInfo
        const data = { orderDto, limit }

        const res = await findArticles(data)
        tableInfo.recommentArticles = res.data.data.articles
    } catch (error) {
    }
}

const initAccountment = async () => {
    const res = await getAnnouncement()
    informDate.announment = res.data.data
}



const toArticleDetail = (id: number) => {
    router.push({ name: 'article_detail', params: { id } })
}
//分页器
const sizeChange = (pageSize: number) => {
    tableInfo.pageSize = pageSize
    initTableInfo()

}
const currentChange = (page: number) => {
    tableInfo.page = page
    initTableInfo()
}

//打开对话框
const openInformDialog = () => {
    informDate.announcementDialog = true
}

const pubishAnnouncent = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid, error) => {
        if (valid) {
            const { content, title } = informDate
            try {
                const { data } = await addAnnouncement({ content, title })
                initAccountment()
                informDate.announcementDialog = false
                resetForm(formEl)
                ElMessage({
                    type: 'success',
                    message: data.msg
                })
            } catch (error) {
            }
        }
    })

}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
</script>
<style scoped lang="scss">
.container {
    display: flex;
    width: 100%;
    height: 100%;

    .aside {
        min-width: 400px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .table-container {
        min-width: 600px;
        width: 100%;
        margin: 0 20px;
        padding: 10px;

        .pagination {
            margin-top: 10px;
            display: flex;
            justify-content: end;
        }
    }

    .right-contaienr {
        min-width: 400px;
        height: 100%;
    }

    .my-header {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
    }

    .introduction-box {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}
</style>